package home.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.layout.SingleLayoutHelper;
import com.bumptech.glide.Glide;

import net.ck.hzq.NewsWebViewActivity;
import net.ck.hzq.R;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import Utils.ScreenUtil;
import dao.HomeNewsBean;

/**
 * by BF00233 on 2018/12/10.
 */
public class NewsAdapter extends DelegateAdapter.Adapter<NewsAdapter.NewsVH> {

    private final Context mContext;
    private List<HomeNewsBean> mData;

    public NewsAdapter(Context context) {
        mContext = context;
        mData = new ArrayList<>();
    }

    public void setupData(List<HomeNewsBean> data) {
        mData.clear();
        if (data != null) {
            mData.addAll(data);
        }
        notifyDataSetChanged();
    }

    @Override
    public LayoutHelper onCreateLayoutHelper() {
        SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
        layoutHelper.setMarginBottom(ScreenUtil.dip2px(mContext, 10));
        return layoutHelper;
    }

    @NonNull
    @Override
    public NewsVH onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        return new NewsVH(LayoutInflater.from(mContext).inflate(R.layout.item_home_news, viewGroup, false));
    }

    @Override
    public void onBindViewHolder(@NonNull NewsVH holder, int position) {
        if (position < 0 || position >= mData.size()) {
            return;
        }
        HomeNewsBean bean = mData.get(position);
        Glide.with(mContext).load(bean.getNewImag()).into(holder.cover);
        holder.title.setText(bean.getBt());
        Date date = new Date(bean.getPushDate());
        java.text.DateFormat format1 = new java.text.SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        holder.date.setText(format1.format(date));
        holder.readNumber.setText(bean.getReadNumber() + "阅读");

        holder.itemView.setOnClickListener(v -> {
            NewsWebViewActivity.start(mContext, bean);
        });
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    class NewsVH extends RecyclerView.ViewHolder {
        private ImageView cover;
        private TextView title;
        private TextView readNumber;
        private TextView date;

        NewsVH(@NonNull View itemView) {
            super(itemView);
            cover = itemView.findViewById(R.id.news_cover);
            title = itemView.findViewById(R.id.news_title);
            readNumber = itemView.findViewById(R.id.read_number);
            date = itemView.findViewById(R.id.date);
        }
    }

}
